<template>
  <div class="order-procure">
    <div class="switch-wrap jzt-flex-center">
      <div class="cg-auto jzt-flex-center mr40">
        <el-switch v-model="switchForm.isAutoTaking" :active-value="1" :inactive-value="0" @change="saveConfigFun" />
        <div class="jzt-flex-center">
          <p class="ml10 mr6">采购单自动接单</p>
          <el-popover
            placement="bottom"
            :width="200"
            popper-class="f12"
            trigger="hover"
            content="开启后，采购单，待接单将自动接单，无需手动接单。"
          >
            <template #reference>
              <el-icon><QuestionFilled /></el-icon>
            </template>
          </el-popover>
        </div>
      </div>
      <div class="tui-cg-auto jzt-flex-center">
        <el-switch v-model="switchForm.isAutoRefund" :active-value="1" :inactive-value="0" @change="saveConfigFun" />
        <div class="jzt-flex-center">
          <p class="ml10 mr6">退采购单自动接单</p>
          <el-popover
            placement="bottom"
            :width="200"
            popper-class="f12"
            trigger="hover"
            content="开启后，已接单的采购单申请退单时将自动接单，无需手动接单。"
          >
            <template #reference>
              <el-icon><QuestionFilled /></el-icon>
            </template>
          </el-popover>
        </div>
      </div>
    </div>

    <!-- 搜索表单 -->
    <div class="search-wrap mt20">
      <SearchForm
        ref="searchFormRef"
        colBtn
        :list="[...formList]"
        @submit="search"
        @reset="reset"
        @daterangeChange="daterangeChange"
      ></SearchForm>
    </div>

    <div class="middle pt20">
      <el-tabs v-model="activeName" @tab-change="getList">
        <el-tab-pane :label="'全部'" name="1"></el-tab-pane>
        <el-tab-pane :label="'待接单'" name="2"></el-tab-pane>
        <el-tab-pane :label="'已拒绝接单'" name="3"></el-tab-pane>
        <el-tab-pane :label="'已撤销'" name="20"></el-tab-pane>
        <el-tab-pane :label="'待发货'" name="4"></el-tab-pane>
        <el-tab-pane :label="'部分发货'" name="5"></el-tab-pane>
        <el-tab-pane :label="'已发货'" name="6"></el-tab-pane>
        <el-tab-pane :label="'已关闭'" name="9"></el-tab-pane>
        <el-tab-pane :label="'售后'" name="-1"></el-tab-pane>
      </el-tabs>

      <!-- 今日/昨日/近7日/近30日等，创建订单按钮，关键词搜索 -->
      <div class="center-search-wrap">
        <div>
          <div class="left">
            <div class="date-filter">
              <el-radio-group v-model="postData.date" @change="changeDate">
                <el-radio-button label="今天" :value="0" />
                <el-radio-button label="昨天" :value="1" />
                <el-radio-button label="近7天" :value="7" />
                <el-radio-button label="近30天" :value="30" />
              </el-radio-group>
            </div>
            <el-radio-group class="ml40" v-model="radioVal" v-if="activeName === '2'" @change="getList">
              <!-- <el-radio-group class="ml40" v-model="radioVal" v-if="activeName === '2'"> -->
              <el-radio value="1">采购订单</el-radio>
              <el-radio value="2">退采购订单</el-radio>
            </el-radio-group>
          </div>
          <div class="right">
            <!-- <el-input v-model="postData.searchkey" style="max-width: 600px" placeholder="请输入">
              <template #prepend>
                <el-select v-model="postData.key" :placeholder="'请选择'" style="width: 100px">
                  <el-option v-for="_item in options" :key="_item.value" :label="_item.label" :value="_item.value" />
                </el-select>
              </template>
              <template #append> </template>
            </el-input>
            <el-button class="ml10" type="primary" plain :icon="RefreshRight" @click="resetCenter">重置</el-button> -->
          </div>
        </div>
      </div>
    </div>

    <!-- 表单数据 -->
    <div class="products-list" style="height: calc(100vh - 535px); overflow: auto">
      <div class="my-table" style="min-width: 1100px" v-if="list.length > 0">
        <div class="table-header">
          <div>
            <div class="row">
              <div class="col1" style="min-width: 120px">采购编码</div>
              <div class="col4">商品种类信息</div>
              <div class="col5">数量</div>
              <div class="col5">件数</div>
              <div class="col4">采购商家</div>
              <div class="col4">收款计划</div>
              <div class="col4">应收总金额</div>
              <div class="col4">本次应收金额</div>
              <div class="col4">订单已收金额</div>
              <div class="col4">订单未收金额</div>
              <div class="col5">税额</div>
              <div class="col5">是否开票</div>
              <div class="col4">是否回传发票</div>
              <div class="col5">付款状态</div>
              <div class="col4">下单时间</div>
              <div class="col4">配送方式</div>
              <div class="col4">售后状态</div>
              <div class="col6">操作</div>
            </div>
          </div>
        </div>

        <div class="table-body">
          <div class="list-item" v-for="(item, index) in list" :key="index">
            <div class="tpis-head">
              <div class="jzt-flex-start">
                <p class="blue" v-if="[5].includes(item.factoryState)">部分发货</p>
                <p class="green" v-else-if="[6].includes(item.factoryState)">已发货</p>
                <p class="orange" v-else-if="[4, 2].includes(item.factoryState)">
                  {{ item.factoryState === 4 ? "待发货" : "待接单" }}
                </p>
                <p class="red" v-else-if="[3, 20].includes(item.factoryState)">
                  {{ item.factoryState === 3 ? "已拒绝" : "已撤销" }}
                </p>
                <p class="gray" v-else-if="[9].includes(item.factoryState)">已关闭</p>
                <p v-else class="gray">-</p>

                <div v-show="[4, 5].includes(item.factoryState)" class="jzt-flex-center">
                  <p>预计发货时间：{{ item.expectShipmentTime || "-" }}</p>
                  <p class="jzt-flex-center ml32 mr40">
                    <span style="color: #ff3333">发货倒计时：</span>
                    <CountdownMy :timestamp="new Date(item.expectShipmentTime).getTime()" />
                  </p>
                </div>

                <p class="mr40 jzt-flex-center" v-if="item.isBusinessInvoice === 1">
                  <el-icon class="mr8" style="color: #ff9900"><WarningFilled /></el-icon>
                  采购商选择了开发票，请致电沟通后再进行接单!
                </p>

                <el-button
                  v-if="item.isProduceConfirmState === 1"
                  type="primary"
                  size="small"
                  @click="openEditor(1, 'edit', item)"
                  >发起生产完成确认</el-button
                >
                <el-button
                  v-if="item.isInstallConfirmState === 1"
                  type="primary"
                  size="small"
                  @click="openEditor(2, 'edit', item)"
                  >发起安装完成确认</el-button
                >
                <el-button v-if="item.isSelfPickupState === 2" type="primary" size="small" @click="openEditor(3, 'edit', item)">
                  自提货确认
                </el-button>
                <el-button
                  v-if="item.isDistributeConfirmState === 3"
                  type="primary"
                  size="small"
                  @click="openEditor(4, 'edit', item)"
                >
                  发起配送完成确认
                </el-button>
                <!-- =================================================================== -->
                <!-- 生产 -->
                <el-button
                  v-if="[2, 3, 4].includes(item.isProduceConfirmState)"
                  :type="item.isProduceConfirmState === 2 ? 'primary' : item.isProduceConfirmState === 3 ? 'primary' : 'danger'"
                  size="small"
                  plain
                  @click="
                    () => {
                      if (item.isProduceConfirmState === 4) {
                        openEditor(1, 'refuse', item);
                      } else {
                        openEditor(1, 'view', item);
                      }
                    }
                  "
                >
                  {{ getStateName(1, item.isProduceConfirmState) }}
                </el-button>
                <!-- 安装 -->
                <el-button
                  v-if="[2, 3, 4].includes(item.isInstallConfirmState)"
                  :type="item.isInstallConfirmState === 2 ? 'primary' : item.isInstallConfirmState === 3 ? 'primary' : 'danger'"
                  size="small"
                  plain
                  @click="
                    () => {
                      if (item.isInstallConfirmState === 4) {
                        openEditor(2, 'refuse', item);
                      } else {
                        openEditor(2, 'view', item);
                      }
                    }
                  "
                >
                  {{ getStateName(2, item.isInstallConfirmState) }}
                </el-button>
                <!-- 自提货 -->
                <el-button
                  v-if="[3, 4, 5].includes(item.isSelfPickupState)"
                  :type="item.isSelfPickupState === 3 ? 'primary' : item.isSelfPickupState === 4 ? 'primary' : 'danger'"
                  size="small"
                  plain
                  @click="
                    () => {
                      if (item.isSelfPickupState === 5) {
                        openEditor(3, 'refuse', item);
                      } else {
                        openEditor(3, 'view', item);
                      }
                    }
                  "
                >
                  {{ getStateName(3, item.isSelfPickupState) }}
                </el-button>
                <!-- 配送 -->
                <el-button
                  v-if="[4, 5, 6].includes(item.isDistributeConfirmState)"
                  :type="
                    item.isDistributeConfirmState === 4 ? 'primary' : item.isDistributeConfirmState === 5 ? 'primary' : 'danger'
                  "
                  size="small"
                  plain
                  @click="
                    () => {
                      if (item.isDistributeConfirmState === 6) {
                        openEditor(4, 'refuse', item);
                      } else {
                        openEditor(4, 'view', item);
                      }
                    }
                  "
                >
                  {{ getStateName(4, item.isDistributeConfirmState) }}
                </el-button>
              </div>
            </div>
            <div class="row">
              <div class="col1">
                <!-- 采购编码 -->
                <el-button class="border" type="primary" link :title="item.purchaseOrderNo" @click="toPathDetail(item)">
                  {{ item.purchaseOrderNo }}
                </el-button>
              </div>
              <div class="col4">
                <!-- 商品种类信息 -->
                {{ item.categoryNum || 0 }}种商品/({{ item.detailNum || 0 }}件)
              </div>
              <div class="col5">
                <!-- 数量 -->
                {{ item.goodsNum }}
              </div>
              <div class="col5">
                <!-- 件数 -->
                {{ item.detailNum }}
              </div>
              <div class="col4">
                <!-- 采购商家 -->
                {{ item.merchantName }}
              </div>
              <div class="col4">
                <!-- 收款计划 -->
                <el-button
                  v-if="item.payPlanList?.length > 0"
                  class="border"
                  type="primary"
                  link
                  @click="openPlanDetail(item)"
                  :title="getPlanName(item)"
                >
                  {{ getPlanName(item) }}
                </el-button>
                <span v-else>-</span>
              </div>
              <div class="col4">
                <!-- 应收总金额 -->
                {{ item.payableTotalAmountFactory }}
              </div>
              <div class="col4">
                <!-- 本次应收金额 -->
                {{ item.currentPayableAmountFactory }}
              </div>
              <div class="col4">
                <!-- 订单已收金额 -->
                {{ item.factoryActualTotalAmount }}
              </div>
              <div class="col4">
                <!-- 订单未收金额 -->
                {{ item.factoryRemainTotalAmount }}
              </div>
              <div class="col5">
                <!-- 税额 -->
                {{ item.invoiceAmount }}
              </div>
              <div class="col5">
                <!-- 是否开票 -->
                {{ item.isBusinessInvoice === 1 ? "是" : "否" }}
              </div>
              <div class="col4">
                <!-- 是否回传发票 -->
                {{ item.isUploadInvoice === 1 ? "是" : "否" }}
              </div>
              <div class="col5">
                <!-- 付款状态 -->
                <el-tag type="primary" v-show="item.payStatus === 2">部分支付</el-tag>
                <el-tag type="success" v-show="item.payStatus === 3">已支付</el-tag>
                <el-tag type="warning" v-show="item.payStatus === 1">待支付</el-tag>
              </div>
              <div class="col4">
                <!-- 下单时间 -->
                {{ item.orderTime }}
              </div>
              <div class="col4">
                <!-- 配送方式 -->
                {{ item.deliveryRoute === 1 ? "快递" : "-" }}
              </div>
              <div class="col4">
                <!-- 售后状态 -->
                <el-tag type="primary" v-show="item.afterSaleStatus === 1">售后中</el-tag>
                <el-tag type="success" v-show="item.afterSaleStatus === 2">售后结束</el-tag>
              </div>
              <div class="col6">
                <!-- 操作 -->
                <div>
                  <el-button link type="primary" size="small" @click="toPathDetail(item)"> 查看 </el-button>
                  <el-button
                    link
                    class="ml0"
                    type="primary"
                    size="small"
                    @click="
                      toPath({
                        path: '/order/procure/list',
                        query: { purchaseOrderId: item.purchaseOrderId, redirect: `/order/procure`, tabs: activeName }
                      })
                    "
                  >
                    清单
                  </el-button>
                  <el-button
                    v-if="item.showShipState === 1"
                    class="ml0"
                    link
                    type="primary"
                    size="small"
                    @click="
                      toPath({
                        path: '/order/procure/send',
                        query: { purchaseOrderId: item.purchaseOrderId, redirect: `/order/procure`, tabs: activeName }
                      })
                    "
                  >
                    发货
                  </el-button>

                  <el-button
                    v-if="item.isDistributeConfirmState === 2"
                    class="ml0"
                    link
                    type="primary"
                    size="small"
                    @click="
                      toPath({
                        path: '/order/procure/delivery',
                        query: { purchaseOrderId: item.purchaseOrderId, redirect: `/order/procure`, tabs: activeName }
                      })
                    "
                  >
                    开始配送
                  </el-button>
                  <el-button
                    class="ml0"
                    link
                    type="primary"
                    size="small"
                    v-if="activeName === '9' || item.factoryState === 20"
                    @click="
                      () => {
                        currObj = item;
                        clickDel();
                      }
                    "
                    >删除</el-button
                  >
                  <div
                    v-show="
                      item.businessState === 2 || item.factoryState === 5 || item.factoryState === 6 || item.factoryState === 21
                    "
                    style="display: inline-block"
                  >
                    <el-popover placement="bottom-end" popper-class="action-more" teleported :width="100" trigger="hover">
                      <template #reference>
                        <el-button link type="primary" size="small">更多</el-button>
                      </template>
                      <div class="action-btn">
                        <p>
                          <el-button
                            v-if="item.businessState === 2 && !(activeName === '2' && radioVal === '2')"
                            link
                            type="primary"
                            size="small"
                            style="width: 100%; justify-content: flex-start"
                            @click="
                              () => {
                                currObj = item;
                                clickReceive();
                              }
                            "
                          >
                            接单
                          </el-button>
                        </p>
                        <p>
                          <el-button
                            v-if="item.businessState === 2 && !(activeName === '2' && radioVal === '2')"
                            link
                            type="primary"
                            size="small"
                            style="width: 100%; justify-content: flex-start"
                            @click="
                              () => {
                                currObj = item;
                                handleOpenReject();
                              }
                            "
                          >
                            拒绝订单
                          </el-button>
                        </p>
                        <p>
                          <el-button
                            v-show="item.factoryState === 5 || item.factoryState === 6"
                            link
                            type="primary"
                            size="small"
                            style="width: 100%; justify-content: flex-start"
                            @click="toPathDetail(item)"
                          >
                            修改物流
                          </el-button>
                        </p>
                        <p>
                          <el-button
                            v-show="item.factoryState === 21"
                            link
                            type="primary"
                            size="small"
                            style="width: 100%; justify-content: flex-start"
                            @click="clickCancel(item)"
                          >
                            同意撤销
                          </el-button>
                        </p>
                        <p>
                          <el-button
                            v-show="item.factoryState === 21"
                            link
                            type="danger"
                            size="small"
                            style="width: 100%; justify-content: flex-start"
                            @click="clickRefuseRevoke(item)"
                          >
                            拒绝撤销
                          </el-button>
                        </p>
                      </div>
                    </el-popover>
                  </div>
                </div>
              </div>
            </div>
            <div class="tips">
              <p class="mb4 f12">关联客户：{{ item.customer }}</p>
              <p class="f12">
                收货信息：{{ item.receivingName }} / {{ item.receivingMobile }} /
                {{ item.receivingAreaDetail ? item.receivingAreaDetail + item.receivingAddress : "-" }}
              </p>
            </div>
          </div>
        </div>
      </div>
      <div v-else style="display: flex; justify-content: center; width: 100%">
        <el-empty description="这里暂时什么都没有" />
      </div>
    </div>

    <div class="pt20" style="display: flex; justify-content: flex-end">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="pagination.sizes"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 拒绝订单弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="'拒绝订单'"
      width="500"
      align-center
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="handleClose"
    >
      <template #header>
        <p><i class="icon"></i>拒绝订单</p>
      </template>
      <div class="form-wrap">
        <el-form :model="form" ref="formRef" label-width="auto" style="max-width: 600px">
          <el-form-item
            prop="refuseType"
            label="取消原因"
            :rules="{ required: true, message: '请选择', trigger: ['blur', 'change'] }"
          >
            <el-select v-model="form.refuseType" placeholder="请选择" clearable>
              <el-option v-for="item in causeList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item prop="refuseRemarks" label="备注">
            <el-input
              :rows="2"
              type="textarea"
              placeholder="请输入"
              v-model="form.refuseRemarks"
              oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button class="jzt-button" type="info" @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="refuseOrderSubmit">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 确认删除 -->
    <ActionSubmitDialog
      v-model:isOpen="_isOpenDel"
      :message="'删除后，当前采购单将被永久删除，请谨慎操作，是否继续删除？'"
      :submitBtnText="'确认'"
      @submit="returnSubmitDel"
    />
    <!-- 确认接单 -->
    <ActionSubmitDialog2
      v-model:isOpen="_isOpenReceive"
      :type="'info'"
      :cycleTime="receiveInfo.cycleTime"
      :redText="receiveInfo.redText"
      :sendTime="receiveInfo.sendTime"
      :message="'您正在操作接单确认，接单后，请务必在交货周期内按时发货！'"
      :submitBtnText="'确认接单'"
      @submit="returnSubmitReceive"
    />
    <!-- 同意撤销 二次确认 -->
    <ActionSubmitDialog
      v-model:isOpen="_isOpenCancel"
      :message="cancelTitle"
      :submitBtnText="'确认撤销'"
      @submit="returnSubmitCancel"
    />
    <!-- 拒绝撤销弹窗 -->
    <el-dialog
      v-model="dialogVisible2"
      :title="'拒绝撤销订单'"
      width="500"
      align-center
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="handleClose2"
    >
      <template #header>
        <p><i class="icon"></i>拒绝撤销订单</p>
      </template>
      <div class="form-wrap">
        <el-form :model="form2" ref="formRef2" label-width="auto" style="max-width: 600px">
          <el-form-item
            prop="cancelRejectType"
            label="取消原因"
            :rules="{ required: true, message: '请选择', trigger: ['blur', 'change'] }"
          >
            <el-select v-model="form2.cancelRejectType" placeholder="请选择" clearable>
              <el-option v-for="item in causeList2" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item prop="cancelRejectRemark" label="备注">
            <el-input
              :rows="2"
              type="textarea"
              placeholder="请输入"
              v-model="form2.cancelRejectRemark"
              oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button class="jzt-button" type="info" @click="dialogVisible2 = false">取消</el-button>
          <el-button type="primary" @click="refuseRevokeSubmit">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 收款计划明细 -->
    <PaymentPlan v-model:isOpen="_isOpenPlan" :optionInfo="optionInfoPlan" />

    <!-- 发货、生产审核拒绝 | 自提货、配送审核拒绝 | 安装、安装审核拒绝  弹窗 -->
    <EditorDialog
      v-model:isOpen="_isOpenEditor"
      :type="editorDialogInfo.type"
      :title="editorDialogInfo.title"
      :titleTips="editorDialogInfo.titleTips"
      :submitBtnText="editorDialogInfo.submitBtnText"
      :refuseVal="editorDialogInfo.refuseVal"
      :refuseReason="editorDialogInfo.refuseReason"
      :editorVal="editorDialogInfo.editorVal"
      :submitFun="editorDialogInfo.submitFun"
    />
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted } from "vue";
import SearchForm from "@/components/SearchForm";
import { Search, RefreshRight, WarningFilled, QuestionFilled } from "@element-plus/icons-vue";
import ActionSubmitDialog from "@/components/ActionSubmitDialog";
import ActionSubmitDialog2 from "./components/ActionSubmitDialog";
import EditorDialog from "./components/editorDialog.vue";
import {
  getProcureList,
  delOrder,
  acceptOrder,
  refuseOrder,
  approvalCancel,
  confirmProduceFinish,
  confirmSelfPickup,
  confirmInstallFinish,
  confirmDistributeFinish,
  getConfirmMsg,
  getExpectedDeliveryTime,
  getConfig,
  saveConfig
} from "@/apis/order/procure";
import moment from "moment";
import { ElMessage } from "element-plus";
import { _throttle } from "@/utils";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
import CountdownMy from "@/views/order/measure/components/countdown";
import PaymentPlan from "@/views/order/payment/components/paymentPlan";

const isChainTenant = JSON.parse(localStorage.getItem("userinfo"))?.isChainTenant; //判断是否是加盟商
const radioVal = ref("1");
const options = ref([
  { label: "全部", value: 0 },
  { label: "采购编码", value: 1 },
  { label: "姓名", value: 2 },
  { label: "手机号", value: 3 }
]);
const formList = ref([
  {
    label: "售后状态",
    model: "afterSaleStatus",
    type: "select",
    labelWidth: "90",
    data: [
      { label: "售后中", value: 1 },
      { label: "售后结束", value: 2 }
    ]
  },
  {
    label: "付款状态",
    model: "payStatus",
    type: "select",
    labelWidth: "100",
    data: [
      { label: "待付款", value: 1 },
      { label: "部分付款", value: 2 },
      { label: "已付款", value: 3 }
    ]
  },
  {
    label: "采购商名称",
    model: "merchantName",
    type: "input",
    labelWidth: "90"
  },
  {
    label: "下单时间",
    model: "orderTime",
    type: "daterange",
    labelWidth: "90"
  },
  {
    label: "订单搜索",
    model: "ddKey-ddKeyword",
    type: "select-input",
    labelWidth: "100",
    data: [
      {
        value: "1",
        label: "全部"
      },
      {
        value: "2",
        label: "收货姓名"
      },
      {
        value: "3",
        label: "收货电话"
      },
      {
        value: "4",
        label: "采购编码"
      }
    ]
  },
  {
    label: "客户信息",
    model: "khKey-customerKeyword",
    type: "select-input",
    labelWidth: "90",
    data: [
      {
        value: "1",
        label: "全部"
      },
      {
        value: "2",
        label: "姓名"
      },
      {
        value: "3",
        label: "电话"
      }
    ]
  },
  {
    label: "是否开票",
    model: "isBusinessInvoice",
    type: "select",
    labelWidth: "90",
    data: [
      {
        value: 1,
        label: "是"
      },
      {
        value: 0,
        label: "否"
      }
    ]
  },
  {
    label: "是否回传发票",
    model: "isUploadInvoice",
    type: "select",
    labelWidth: "100",
    data: [
      {
        value: 1,
        label: "是"
      },
      {
        value: 0,
        label: "否"
      }
    ]
  }
]);
const searchFormRef = ref();
const formData = ref({});
const postData = ref({ date: null });
const list = ref([]);
const pagination = ref({
  page: 1,
  size: 10,
  sizes: [10, 20, 30, 40, 50],
  total: 0
});
const optionInfo = ref({ isShow: false });
const activeName = ref("1");
const dialogVisible = ref(false); //拒绝订单-弹窗
const form = ref({}); //拒绝订单表单
const formRef = ref();
const causeList = ref([
  { label: "原材料上涨", value: 1 },
  { label: "商品停产", value: 2 },
  { label: "缺货无法交易", value: 3 },
  { label: "其他原因", value: 4 }
]); //取消原因 下拉数据
const _isOpenDel = ref(false);
const _isOpenReceive = ref(false);
const _isOpenCancel = ref(false);
const receiveInfo = ref({
  cycleTime: 0,
  redText: "",
  sendTime: "-"
});
const cancelTitle = ref(
  "您正在操作撤销采购单审核确认，确认撤销前请详细核查订单信息，通过后此订单将作废，请谨慎操作，是否继续撤销！"
);
const currObj = ref({}); //当前点击的行 订单对象
const dialogVisible2 = ref(false); //拒绝撤销-弹窗
const form2 = ref({}); //拒绝撤销表单
const formRef2 = ref();
const causeList2 = ref([
  { label: "原料已采购", value: 1 },
  { label: "订单已安排生产", value: 2 },
  { label: "部分商品已生产", value: 3 },
  { label: "其他原因", value: 4 }
]); //拒绝原因 下拉数据
const _isOpenPlan = ref(false);
const optionInfoPlan = ref({ detail: [] });
const _isOpenEditor = ref(false); //发货、生产审核拒绝、自提货、配送审核拒绝、安装、安装审核拒绝  弹窗
const editorDialogInfo = ref({});
const switchForm = ref({ isAutoTaking: 0, isAutoRefund: 0 });

onMounted(() => {
  getList();
  setRouteTabs();
  getConfigFun();
});

const saveConfigFun = _throttle(() => {
  saveConfig(switchForm.value).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "设置成功~",
        type: "success"
      });
      getConfigFun();
    }
  });
}, 1000);

//获取工厂端自动配置
const getConfigFun = () => {
  getConfig({ factoryId: JSON.parse(localStorage.getItem("userinfo"))?.tenantId }).then(res => {
    if (res.code === 200) {
      switchForm.value = res.data;
    }
  });
};

const getPlanName = row => {
  const firstPlan = row.payPlanList[0];
  const arr = [
    { label: "接采购单即付款", val: 1 },
    { label: "生产完成确认", val: 2 },
    { label: "发货完成", val: 3 },
    { label: " 入库确认", val: 4 },
    { label: "配送完成确认", val: 5 },
    { label: "安装完成确认", val: 6 }
  ];
  const obj = arr.find(item => item.val === firstPlan.collectionNode);
  return `${firstPlan.collectionType}期款项-${obj?.label || "--"}：¥${firstPlan.payableAmount}`;
};

/**
 *
 * @param row 打开收款计划明细-弹窗
 */
const openPlanDetail = row => {
  currObj.value = row;
  optionInfoPlan.value.detail = { ...row };
  _isOpenPlan.value = true;
};

/**
 *
 * @param type 1-生产  2-安装 3-自提货 4-配送
 * @param val 状态值
 */
const getStateName = (type, val) => {
  let Arr = [];
  if (type === 1) {
    Arr = [
      { label: "待发起生产确认", val: 1 },
      { label: "已发起生产确认", val: 2 },
      { label: "生产完成确认成功", val: 3 },
      { label: "生产完成确认失败", val: 4 }
    ];
  } else if (type === 2) {
    Arr = [
      { label: "待发起安装确认", val: 1 },
      { label: "已发起安装确认", val: 2 },
      { label: "安装完成确认成功", val: 3 },
      { label: "安装完成确认失败", val: 4 }
    ];
  } else if (type === 3) {
    Arr = [
      { label: "不可自提货", val: 1 },
      { label: "待自提货确认", val: 2 },
      { label: "已发起自提货确认", val: 3 },
      { label: "自提货确认成功", val: 4 },
      { label: "自提货确认失败", val: 5 }
    ];
  } else if (type === 4) {
    Arr = [
      { label: "不可配送", val: 1 },
      { label: "待配送", val: 2 },
      { label: "待配送完成确认", val: 3 },
      { label: "已发起配送完成确认", val: 4 },
      { label: "配送完成确认成功", val: 5 },
      { label: "配送完成确认失败", val: 6 }
    ];
  }
  const obj = Arr.find(item => item.val === val);
  return obj.label || "-";
};

/**
 *
 * @param stage 1-生产  2-安装 3-自提货 4-配送
 * @param type edit-编辑 refuse-拒绝 view-只读查看
 * @param row 点击的当前行数据
 */
const openEditor = async (stage = 1, type, row) => {
  currObj.value = row;
  console.log("currObj========", currObj.value);

  //获取确认消息
  const res = await getConfirmMsg({
    type: stage === 1 ? 1 : stage === 2 ? 4 : stage === 3 ? 3 : 2,
    purchaseOrderId: currObj.value.purchaseOrderId
  });
  console.log("获取确认消息", res.data);
  editorDialogInfo.value.type = type;
  editorDialogInfo.value.editorVal = res.data.remark || "";
  // editorDialogInfo.value.editorVal = "这是备注信息";
  if (stage === 1) {
    editorDialogInfo.value.title = "发货确认";
    editorDialogInfo.value.titleTips = "提交后需等采购商确认后生效";
    editorDialogInfo.value.submitFun = confirmProduceFinishFun;
  } else if (stage === 2) {
    editorDialogInfo.value.title = "安装完成确认";
    editorDialogInfo.value.titleTips = "提交后需等采购商确认后生效";
    editorDialogInfo.value.submitFun = confirmInstallFinishFun;
  } else if (stage === 3) {
    editorDialogInfo.value.title = "自提货完成确认";
    editorDialogInfo.value.titleTips = "请确保采购商已上门自提，提交后需要采购商确认！";
    editorDialogInfo.value.submitFun = confirmSelfPickupFun;
  } else if (stage === 4) {
    editorDialogInfo.value.title = "配送完成确认";
    editorDialogInfo.value.titleTips = "提交后需等采购商确认后生效";
    editorDialogInfo.value.submitFun = confirmDistributeFinishFun;
  }
  if (type === "refuse") {
    editorDialogInfo.value.submitBtnText = "重新提交";
    editorDialogInfo.value.refuseReason = res.data.refuseReason; //拒绝原因 refuseReason
    editorDialogInfo.value.refuseVal = res.data.refuseRemark; //拒绝备注 富文本 refuseRemark
    //   editorDialogInfo.value.refuseVal = `<p>222</p><div data-w-e-type="video" data-w-e-is-void>
    // <video poster="" controls="true" width="auto" height="auto"><source src="https://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/mall/2024-09-04/qq1725420238058.mp4" type="video/mp4"/></video>
    // </div><p><br></p>`;
  } else if (type === "view") {
    editorDialogInfo.value.submitBtnText = "";
    editorDialogInfo.value.refuseVal = "";
  } else if (type === "edit") {
    editorDialogInfo.value.submitBtnText = "确认提交";
    editorDialogInfo.value.refuseVal = "";
  }

  _isOpenEditor.value = true;
};

//1-发起生产完成确认
const confirmProduceFinishFun = remark => {
  confirmProduceFinish({ remark, purchaseOrderId: currObj.value.purchaseOrderId }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "已发起生产完成确认",
        type: "success"
      });
      getList();
      _isOpenEditor.value = false;
    }
  });
};

//2-发起安装完成确认
const confirmInstallFinishFun = remark => {
  confirmInstallFinish({ remark, purchaseOrderId: currObj.value.purchaseOrderId }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "已发起安装完成确认",
        type: "success"
      });
      getList();
      _isOpenEditor.value = false;
    }
  });
};

//3-发起自提货完成确认
const confirmSelfPickupFun = remark => {
  confirmSelfPickup({ remark, purchaseOrderId: currObj.value.purchaseOrderId }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "已发起自提货完成确认",
        type: "success"
      });
      getList();
      _isOpenEditor.value = false;
    }
  });
};

//4-发起配送完成确认
const confirmDistributeFinishFun = remark => {
  confirmDistributeFinish({ remark, purchaseOrderId: currObj.value.purchaseOrderId }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "已发起配送完成确认",
        type: "success"
      });
      getList();
      _isOpenEditor.value = false;
    }
  });
};

/**
 * 拒绝撤销
 */
const refuseRevokeSubmit = () => {
  formRef2.value.validate(valid => {
    if (valid) {
      const params = {
        opinion: 2, //审核意见。1-同意。2-拒绝
        purchaseOrderId: currObj.value.purchaseOrderId,
        ...form2.value
      };
      approvalCancel(params).then(res => {
        if (res.code === 200) {
          ElMessage({
            message: "已拒绝撤销",
            type: "success"
          });
          handleClose2();
          getList();
        }
      });
    } else {
      console.log("error submit!");
    }
  });
};
//打开拒绝撤销form信息弹窗
const clickRefuseRevoke = row => {
  currObj.value = row;
  dialogVisible2.value = true;
  nextTick(() => {
    formRef2.value.resetFields();
  });
};
//关闭拒绝撤销form信息弹窗
const handleClose2 = () => {
  dialogVisible2.value = false;
};

/**
 * 同意撤销二次弹窗
 */
const clickCancel = row => {
  currObj.value = row;
  cancelTitle.value = `您正在操作（${row.purchaseOrderNo}）撤销采购单审核确认，确认撤销前请详细核查订单信息，通过后此订单将作废，请谨慎操作，是否继续撤销！`;
  _isOpenCancel.value = true;
};
/**
 * 确认“同意撤销”
 */
const returnSubmitCancel = () => {
  const params = {
    opinion: 1, //审核意见。1-同意。2-拒绝
    purchaseOrderId: currObj.value.purchaseOrderId
  };
  approvalCancel(params).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "已同意撤销",
        type: "success"
      });
      _isOpenCancel.value = false;
      getList();
    }
  });
};

const toPath = obj => {
  //打开新页签
  const routeUrl = router.resolve(obj);
  window.open(routeUrl.href, "_blank");
};

/**
 * 跳转到详情页-打开一页新的页签
 */
const toPathDetail = row => {
  const baseRouter = window.microApp.router.getBaseAppRouter();
  const routeUrl = baseRouter.resolve({
    path: "/factory/order/procure/detail",
    query: { purchaseOrderId: row.purchaseOrderId, redirect: "/order/procure", tabs: activeName.value }
  });
  window.open(routeUrl.href, "_blank");
};

/**
 * 地址栏是否带回了tabs参数
 */
const setRouteTabs = () => {
  if (route.query.tabs) {
    const tabs = route.query.tabs;
    activeName.value = tabs;
  }
};

const changeDate = val => {
  const { start, end } = getTimeRange(val);
  formData.value.orderStartTime = start;
  formData.value.orderEndTime = end;
  getList();
};

const daterangeChange = () => {
  postData.value = { date: null };
};

// 打开拒绝订单弹窗
const handleOpenReject = () => {
  dialogVisible.value = true;
  nextTick(() => {
    formRef.value.resetFields();
  });
};
//关闭拒绝订单弹窗
const handleClose = () => {
  dialogVisible.value = false;
};

//确认拒绝订单
const refuseOrderSubmit = () => {
  refuseOrder({
    purchaseOrderId: currObj.value.purchaseOrderId,
    ...form.value
  }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "拒绝订单成功",
        type: "success"
      });
      getList();
      handleClose();
    }
  });
};

//删除弹窗打开
const clickDel = () => {
  _isOpenDel.value = true;
};
//确认删除
const returnSubmitDel = () => {
  delOrder({ purchaseOrderId: currObj.value.purchaseOrderId }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "删除成功",
        type: "success"
      });
      getList();
      _isOpenDel.value = false;
    }
  });
};

//接单弹窗打开
const clickReceive = async () => {
  _isOpenReceive.value = true;

  //这是获取到的预计发货时间信息
  const res = await getExpectedDeliveryTime({
    purchaseOrderId: currObj.value.purchaseOrderId
  });

  receiveInfo.value = {
    cycleTime: res.data?.expectedDeliveryDays || "-",
    redText:
      res.data?.expectedDeliveryDays === res.data?.originExpectedDays
        ? ""
        : `温馨提示：注意采购商修改了周期，原定日期为${res.data?.originExpectedDays}天，预计${res.data?.originExpectedTime}日前`,
    sendTime: res.data?.expectedDeliveryTime || "-"
  };
};
//确认接单
const returnSubmitReceive = () => {
  acceptOrder({ purchaseOrderId: currObj.value.purchaseOrderId }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "接单成功",
        type: "success"
      });
      getList();
      _isOpenReceive.value = false;
    }
  });
};

//查询入库单列表数据
const getList = () => {
  // console.log(11111, getTimeRange(postData.value.date));

  getProcureList({
    ...formData.value,
    ...postData.value,
    page: pagination.value.page,
    size: pagination.value.size,
    factoryState:
      Number(activeName.value) === 2 && radioVal.value === "2"
        ? 21
        : Number(activeName.value) === 1
          ? null
          : Number(activeName.value),
    orderStartTime: postData.value.date ? getTimeRange(postData.value.date).start : formData.value.orderStartTime,
    orderEndTime: postData.value.date ? getTimeRange(postData.value.date).end : formData.value.orderEndTime
  }).then(res => {
    if (res.code === 200) {
      list.value = res.data.records;
      pagination.value.total = res.data.total;
    }
  });
};

const getTimeRange = num => {
  if (num !== null) {
    let start = "";
    let end = "";
    if (num === 0) {
      start = moment().startOf("day").format("YYYY/MM/DD HH:mm:ss"); // 带有时分秒
      end = moment().endOf("day").format("YYYY/MM/DD HH:mm:ss"); // 带有时分秒
    } else if (num === 1) {
      start = moment().subtract(1, "day").startOf("day").format("YYYY/MM/DD HH:mm:ss"); // 带有时分秒
      end = moment().subtract(1, "day").endOf("day").format("YYYY/MM/DD HH:mm:ss"); // 带有时分秒
    } else {
      start = moment()
        .subtract(num - 1, "day")
        .startOf("day")
        .format("YYYY/MM/DD HH:mm:ss"); // 带有时分秒
      end = moment().format("YYYY/MM/DD HH:mm:ss"); // 带有时分秒
    }

    searchFormRef.value.setFormData("orderTime", [start, end]);
    return { start, end };
  }
};

// 表单查询组件submit回调
const search = form => {
  // console.log("查询表单数据===", form);
  if (form) {
    let _form = JSON.parse(JSON.stringify(form));
    _form.orderStartTime = form?.orderTime ? form?.orderTime[0] : null;
    _form.orderEndTime = form?.orderTime ? form?.orderTime[1] : null;
    if (_form.ddKey === "1") {
      // 全部
      _form.orderKeyword = _form.ddKeyword;
    } else if (_form.ddKey === "2") {
      //收货姓名
      _form.receivingName = _form.ddKeyword;
    } else if (_form.ddKey === "3") {
      //收货姓名
      _form.receivingMobile = _form.ddKeyword;
    } else if (_form.ddKey === "4") {
      //采购编码
      _form.purchaseOrderNo = _form.ddKeyword;
    }
    delete _form?.orderTime;
    delete _form?.khKey;
    delete _form?.ddKey;
    delete _form?.ddKeyword;
    formData.value = _form;
  } else {
    formData.value = {};
  }
  nextTick(() => {
    getList();
  });
};
//清空查询表单
const reset = () => {
  search("");
  daterangeChange();
};

const handleSizeChange = val => {
  pagination.value.size = val;
  getList();
};
const handleCurrentChange = val => {
  pagination.value.page = val;
  getList();
};
</script>

<style lang="scss">
.action-more {
  z-index: 2 !important;
  min-width: 0 !important;
}
</style>
<style lang="scss" scoped>
.switch-wrap {
  position: fixed;
  top: 64px;
  right: 20px;
  // padding-left: 200px;
}
:deep(.el-dialog__header) {
  font-size: 18px;
  color: #131414;
  .icon {
    display: inline-block;
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background-color: #007dff;
    margin: 0 8px 4px 0;
  }
}
.order-procure {
  height: calc(100% - 20px);
  overflow-y: auto;
  padding: 0 20px 20px 20px;

  .search-wrap {
    padding: 20px 20px 2px 20px;
    overflow-x: hidden;
    background-color: #f6f8fa;
  }

  .middle {
    position: sticky;
    top: 0;
    background-color: white;
    z-index: 22;
    :deep(.el-tabs__header.is-top) {
      margin-bottom: 0;
    }
  }
  .center-search-wrap {
    :deep(.el-input-group__append) {
      padding: 0;
    }
    // :deep(.el-input-group__prepend) {
    //   padding: 0;
    //   box-shadow: none;
    // }
    // :deep(.el-input.el-input-group.el-input-group--append.el-input-group--prepend) {
    //   & > .el-input-group__prepend {
    //     border-radius: 4px 0 0 4px;
    //     border: 1px solid #dcdfe6;
    //     border-right: none;
    //     .el-input__wrapper {
    //       border-radius: 4px;
    //     }
    //     .el-cascader.el-tooltip__trigger.el-tooltip__trigger {
    //       border-radius: 4px 0 0 4px;
    //     }
    //   }
    //   & > .el-input__wrapper {
    //     border: 1px solid #dcdfe6;
    //   }
    // }
    // :deep(.el-input__wrapper) {
    //   box-shadow: none;
    // }
    & > div {
      display: flex;
      justify-content: space-between;
      padding: 20px 0;
    }
    & > div > div {
      display: flex;
    }
    .left {
      :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
        background-color: white;
        color: #007dff;
      }
    }
  }
}

.products-list {
  .table-header {
    background-color: #f2f6fc;
    margin-bottom: 10px;
    border: 1px solid #e1e6ed;
    position: sticky;
    top: 0px;
    z-index: 2;
  }
  .table-body {
    // max-height: calc(100vh - 345px);
    .blue {
      color: #007dff;
    }
    .gray {
      color: #86909c;
    }
    .green {
      color: #19cc15;
    }
    .orange {
      color: #ff9900;
    }
    .red {
      color: #ff3333;
    }
    // overflow: auto;
    .list-item {
      margin-bottom: 10px;
      & > div {
        border: 1px solid #e1e6ed;
        &.row {
          // display: flex;
          & > div:not(:last-of-type) {
            border-right: 1px solid #e1e6ed;
          }
        }
        & > div {
          display: flex;
          align-items: center;
        }
      }
      .col1 {
        & > div {
          display: flex;
        }

        .left {
          img {
            width: 80px;
            height: 80px;
            border-radius: 4px;
          }
        }
        .right {
          padding-left: 18px;
          .name {
            font-size: 14px;
            color: #3d3d3d;
            margin-bottom: 5px;
          }
          p {
            font-size: 12px;
            color: #86909c;
            margin-bottom: 5px;
          }
        }
      }
      .tpis-head {
        line-height: 24px;
        padding: 8px 20px;
        border-bottom: none;
        background-color: #f5f7fa;
        & > div > p:first-of-type {
          width: 120px;
        }
      }
      .tips {
        padding: 8px 20px;
        border-top: none;
        line-height: 22px;
        box-sizing: border-box;
        color: #4e5969;
      }
    }
  }
  .table-header,
  .table-body {
    & > div > div.row {
      display: grid;
      grid-template-columns: 120px 1fr 60px 60px 1fr 100px 1fr 1fr 1fr 1fr 60px 60px 60px 80px 1fr 60px 60px 1fr;
      & > div {
        padding: 14px 4px;
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        box-sizing: border-box;
        :deep(.el-button.el-button--primary.is-link.border) {
          width: 100%;
          justify-content: flex-start;
          span {
            // white-space: break-spaces;
            // word-break: break-all;
            display: inline-block;
            max-width: 150px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            border-bottom: 1px solid #007dff;
          }
        }
      }
    }
  }
}
</style>
